package dth.bean;

import java.util.ArrayList;
import java.sql.Date;

import javax.faces.bean.ManagedBean;
import javax.faces.model.SelectItem;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

import dth.dao.AccountDAO;
import dth.dao.AdminDAO;
import dth.dao.MovieDAO;
import dth.dao.PackageDAO;
import dth.dao.UserDAO;
import dth.dao.UserDAO;
import dth.dao.UserPackageDAO;
import dth.dao.AccountDAO;
import dth.entity.Account;
import dth.entity.Admin;
import dth.entity.Package;
import dth.entity.User;
import dth.entity.Account;
import dth.entity.UserPackage;
import dth.utils.DthSessionConstant;
import dth.utils.DthUtil;
import antlr.collections.List;

@ManagedBean(name = "accountBean")
public class AccountBean {
	private int userId;//id of user (dis,dealer,account when insert)
	private int adminId;//id of insert admin
	private int id = 0;
	private String adminName;
	private String userName;
	private String password;
	private String rePassword;
	private String old;
	private int fkDealerId;
	private int fkDistributorId;
	private int fkAdminId;
	private int fkUserId;
	private String messExistUsername;
	private String cardNumber;
	private String messInvaildCardNumber;
	
	private int userType;
	private java.util.List<SelectItem> listUser=new ArrayList<SelectItem>();
	
	public java.util.List<SelectItem> getListUser() {
		System.out.println("---vao change list user type:"+userType);
		AccountDAO accountDAO=new AccountDAO();
		if(getUserType()==4)
			listUser=accountDAO.getListUserCmbx();
		else if(getUserType()==2)
			listUser=accountDAO.getListDealerCmbx();
		else if(getUserType()==3)
			listUser=accountDAO.getListDistributorCmbx();
		else
			listUser=accountDAO.getListUserCmbx();//test
		return listUser;
	}

	public void setListUser(java.util.List<SelectItem> listUser) {
		this.listUser = listUser;
	}

	public int getUserType() {
		if(DthUtil.getSession(DthSessionConstant.ACCOUNT_USER_TYPE)==null)
			return 0;
		else
			userType=Integer.parseInt(DthUtil.getSession(DthSessionConstant.ACCOUNT_USER_TYPE).toString());
		return userType;
	}
	
	public int getUserId() {
		if(DthUtil.getSession(DthSessionConstant.ACCOUNT_USER_ID)==null)
			return 0;
		else
			userId=Integer.parseInt(DthUtil.getSession(DthSessionConstant.ACCOUNT_USER_ID).toString());
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public void setUserType(int userType) {
		this.userType = userType;
	}

	public String getMessInvaildCardNumber() {
		System.out.println("----check card number:" + cardNumber);
		if (id != 0 || cardNumber == null || cardNumber.length() == 0) {
			return messInvaildCardNumber;
		}
		UserDAO userDAO = new UserDAO();
		User user = userDAO.checkUserByCardId(cardNumber);
		if (user == null)
			messInvaildCardNumber = "(*)this card id is invaild";
		else
			messInvaildCardNumber = "(*)this card id is vaild";
		return messInvaildCardNumber;
	}

	public int getAdminId() {
		return adminId;
	}

	public void setAdminId(int adminId) {
		this.adminId = adminId;
	}

	public void setMessInvaildCardNumber(String messInvaildCardNumber) {
		this.messInvaildCardNumber = messInvaildCardNumber;
	}

	public String getCardNumber() {
		return cardNumber;
	}

	public void setCardNumber(String cardNumber) {
		this.cardNumber = cardNumber;
	}

	public int getId() {
		return id;
	}

	public String getUserName() {
		return userName;
	}

	public String getPassword() {
		return password;
	}

	public int getFkDealerId() {
		return fkDealerId;
	}

	public int getFkDistributorId() {
		return fkDistributorId;
	}

	public int getFkAdminId() {
		return fkAdminId;
	}

	public int getFkUserId() {
		return fkUserId;
	}

	public String getAdminName() {
		return adminName;
	}

	public void setAdminName(String adminName) {
		this.adminName = adminName;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRePassword() {

		return rePassword;
	}

	public String getMessExistUsername() {
		AccountDAO accountDAO = new AccountDAO();
		System.out.println("---input user name:" + userName);
		if (userName != null) {
			if (accountDAO.checkUserNanmeIsVaild(userName))
				messExistUsername = "";
			else
				messExistUsername = "(*) your username is exist. Please change another";
		}
		return messExistUsername;
	}

	public void setMessExistUsername(String messExistUsername) {
		this.messExistUsername = messExistUsername;
	}

	public void setId(int id) {
		this.id = id;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public void setFkDealerId(int fkDealerId) {
		this.fkDealerId = fkDealerId;
	}

	public void setFkDistributorId(int fkDistributorId) {
		this.fkDistributorId = fkDistributorId;
	}

	public void setFkAdminId(int fkAdminId) {
		this.fkAdminId = fkAdminId;
	}

	public void setFkUserId(int fkUserId) {
		this.fkUserId = fkUserId;
	}

	public void setListAccount(java.util.List<Account> listAccount) {
		this.listAccount = listAccount;
	}

	public void setRePassword(String rePassword) {

		this.rePassword = rePassword;
	}

	private java.util.List<Account> listAccount = new ArrayList<Account>();

	public java.util.List<Account> getListAccount() {
		AccountDAO accDao = new AccountDAO();
		java.util.List<Account> list = accDao.getListAccount();
		list.remove(0);// k hien ra admin chu
		return list;
	}

	public AccountBean() {
		// TODO Auto-generated constructor stub
		System.out.println("---request url:" + DthUtil.getRequestURL());
		if (dth.utils.DthUtil.getRequestURL().contains("account.xhtml")) {
			System.out.println("--vao day role:" + LoginBean.roleCode);
			if (LoginBean.roleCode != 1)
				dth.utils.DthUtil.navigateTo("welcome.xhtml");
		}

		System.out.println("--account bean");
		Object objectAction = dth.utils.DthUtil.getRequest().getParameter(
				"action");
		System.out.println("----------action:" + objectAction);
		if (objectAction != null) {
			if (objectAction.equals("delete")) {
				Object objectId = dth.utils.DthUtil.getRequest().getParameter(
						"user_id");
				if (objectId != null)
					id = Integer.parseInt(objectId.toString());
				System.out.println("---id delete:" + id);
			} else if (objectAction.equals("update")) {
				Object objectId = dth.utils.DthUtil.getRequest().getParameter(
						"user_id");
				if (objectId != null)
					id = Integer.parseInt(objectId.toString());
				System.out.println("---id edit account:" + id);
				for (Account account : getListAccount()) {
					if (account.getUserId() == id) {
						this.userName = account.getUserName();
						this.old = account.getUserPass();
						this.fkAdminId = account.getFkAdminId();
						this.fkDealerId = account.getFkDealerId();
						this.fkDistributorId = account.getFkDistributorId();
						this.fkUserId = account.getFkUserId();
					}
				}
				System.out.println("-----name:" + userName);
			}
		}
	}

	public void insertAdminAccount() {
		if (adminName == null || adminName.length() == 0) {
			dth.utils.DthUtil.showMessage("Message", "Name can not null");
		} else if (password == null || password.length() == 0)
			dth.utils.DthUtil.showMessage("Message", "your pass word is null");
		else if (!password.equals(rePassword))
			dth.utils.DthUtil
					.showMessage("Message", "2 password are not match");
		else if (userName == null || userName.length() == 0)
			dth.utils.DthUtil
					.showMessage("Message", "2 password are not match");
		else{
			try {
				System.out.println("---insert admin account id:" + id);
				System.out.println("---insert admin:" + adminId);

				Admin admin = new Admin();
				admin.setAdminId(adminId);
				admin.setAdminName(adminName);
				AdminDAO adminDAO = new AdminDAO();
				adminDAO.insert(admin);

				/*
				 * create account for admin
				 */
				Account account1 = new Account();
				account1.setUserId(id);
				account1.setUserName(userName);
				account1.setUserPass(dth.utils.DthUtil.convertToMD5(password));
				/*
				 * if insert new get last admin to insert to user
				 */
				if (adminId == 0) {
					java.util.List<Admin> listAdmins = adminDAO.getListAdmin();
					if (listAdmins == null || listAdmins.size() == 0)
						return;
					else {
						adminId = listAdmins.get(listAdmins.size() - 1)
								.getAdminId();
						System.out.println("----id admin vua inset:" + adminId);
						account1.setFkAdminId(adminId);
					}

				} else
					account1.setFkAdminId(adminId);

				account1.setFkDealerId(0);
				account1.setFkDistributorId(0);
				account1.setFkUserId(0);
				java.util.Date date = new java.util.Date();// lay ngay hien tai
				account1.setDateInsert(dth.utils.DthUtil.convertToSqlDate(date));
				AccountDAO accountDAO = new AccountDAO();
				accountDAO.insert(account1);
				dth.utils.DthUtil.showMessage("Message", "Successful create admin account");
			
			} catch (Exception ex) {
				dth.utils.DthUtil.showMessage("Message", "Failed create account");

			}
		}
	}
	/*
	 * insert acc user
	 */
	public void insertAccUser() {
		System.out.println("pass:" + password);
		System.out.println("repass:" + rePassword);
		System.out.println("userID:" + id);
		System.out.println("adminID:" + fkAdminId);
		System.out.println("dealerID:" + fkDealerId);
		System.out.println("distributorID:" + fkDistributorId);
		System.out.println("userID:" + fkUserId);
		AccountDAO accountDAO = new AccountDAO();
		UserDAO userDAO = new UserDAO();
		User user = userDAO.checkUserByCardId(cardNumber);
		if (user == null)
			DthUtil.showMessage("Message", "your card number is invaild");
		else if (!accountDAO.checkUserNanmeIsVaild(userName)) {
			DthUtil.showMessage("Message", "Your username is being used");
		} else if (password == null || password.length() == 0) {
			DthUtil.showMessage("Message", "your password is null");
		} else if (rePassword == null || password.length() == 0)
			DthUtil.showMessage("Message", "yourpassword is null");
		else if (!password.equals(rePassword))
			DthUtil.showMessage("Message", "2 password are not match");
		else if (userName == null || userName.length() == 0)
			DthUtil.showMessage("Message", "user name can not null");
		else {
			System.out.println("---id=" + id);
			try {
				Account account1 = new Account();
				account1.setUserId(0);
				account1.setUserName(userName);
				account1.setUserPass(DthUtil.convertToMD5(password));
				account1.setFkAdminId(fkAdminId);
				account1.setFkDealerId(fkDealerId);
				account1.setFkDistributorId(fkDistributorId);
				account1.setFkUserId(user.getCustomerId());
				java.util.Date date = new java.util.Date();// lay ngay hien tai
				account1.setDateInsert(DthUtil.convertToSqlDate(date));
				int count = 0;
				if (id == 0) {
					System.out.println("inserttttttttt");
					count = accountDAO.insert(account1);

				} else if (id != 0) {
					System.out.println("updateeeeeeeeeeee "
							+ account1.getUserId());
					count = accountDAO.update(account1);

				}

				if (count > 0) {
					DthUtil.navigateTo("login.xhtml?action=signsuccess");
					DthUtil.showMessage("Message",
							"Your account has created. Login to use dth service");
				} else
					DthUtil.showMessageError();
			} catch (Exception ex) {
				DthUtil.showMessageError();
			}
		}

	}
	/*
	 * insert account thien
	 */
	public void insert() {
		System.out.println("pass:" + password);
		System.out.println("repass:" + rePassword);
		System.out.println("oldpass:" + old);
		System.out.println("userID:" + id);
		System.out.println("adminID:" + fkAdminId);
		System.out.println("dealerID:" + fkDealerId);
		System.out.println("distributorID:" + fkDistributorId);
		System.out.println("userID:" + fkUserId);
		AccountDAO accountDAO = new AccountDAO();
		UserDAO userDAO = new UserDAO();
		User user = userDAO.checkUserByCardId(cardNumber);
		if (user == null)
			DthUtil.showMessage("Message", "your card number is invaild");
		else if (!accountDAO.checkUserNanmeIsVaild(userName)) {
			DthUtil.showMessage("Message", "Your username is being used");
		} else if (old == null || old.length() == 0) {
			DthUtil.showMessage("Message", "your password is null");
		} else if (password == null || password.length() == 0) {
			DthUtil.showMessage("Message", "your password is null");
		} else if (rePassword == null || password.length() == 0)
			DthUtil.showMessage("Message", "yourpassword is null");
		else if (!password.equals(rePassword))
			DthUtil.showMessage("Message", "2 password are not match");
		else if (userName == null || userName.length() == 0)
			DthUtil.showMessage("Message", "user name can not null");
		else {
			System.out.println("---id=" + id);
			try {
				Account account1 = new Account();
				account1.setUserId(id);
				account1.setUserName(userName);
				account1.setUserPass(DthUtil.convertToMD5(password));
				account1.setFkAdminId(fkAdminId);
				account1.setFkDealerId(fkDealerId);
				account1.setFkDistributorId(fkDistributorId);
				account1.setFkUserId(user.getCustomerId());
				java.util.Date date = new java.util.Date();// lay ngay hien tai
				account1.setDateInsert(DthUtil.convertToSqlDate(date));
				int count = 0;
				if (id == 0) {
					System.out.println("inserttttttttt");
					count = accountDAO.insert(account1);

				} else if (id != 0) {
					System.out.println("updateeeeeeeeeeee "
							+ account1.getUserId());
					count = accountDAO.update(account1);

				}

				if (count > 0) {
					DthUtil.navigateTo("login.xhtml");
					DthUtil.showMessage("Message",
							"Your account has created. Login to use dth service");
				} else
					DthUtil.showMessageError();
			} catch (Exception ex) {
				DthUtil.showMessageError();
			}
		}

	}
	
	/*
	 * admin insert account for delaer, dis, cus
	 */
	public void insertWithAdminRole(){
		System.out.println("----insertWithAdminRole");
		userId=getUserId();
		userType=getUserType();
		System.out.println("user type:"+userType);
		System.out.println("user id:"+userId);
		if(password==null||password.length()==0)
			DthUtil.showMessage("Message", "your pass word is null");
		else if (userName == null || userName.length() == 0)
			DthUtil.showMessage("Message", "2 password are not match");
		else if(messExistUsername!=null && messExistUsername.length()>1)
			DthUtil.showMessage("Message", "Your username is being used");
		else{
			try{
			System.out.println("information is ok");
			Account account=new Account();
			account.setDateInsert(DthUtil.convertToSqlDate(new java.util.Date()));
			account.setUserName(userName);
			account.setUserPass(DthUtil.convertToMD5(password));
			account.setUserId(0);
			if(userType==2){
				account.setFkAdminId(0);
				account.setFkDealerId(userId);
				account.setFkDistributorId(0);
				account.setFkUserId(0);
			}
			else if(userType==3){
				account.setFkAdminId(0);
				account.setFkDealerId(0);
				account.setFkDistributorId(userId);
				account.setFkUserId(0);
			}
			else if(userType==4){
				account.setFkAdminId(0);
				account.setFkDealerId(0);
				account.setFkDistributorId(0);
				account.setFkUserId(userId);
			}
			AccountDAO accountDAO=new AccountDAO();
			accountDAO.insert(account);
			DthUtil.showMessageSuccess();
			}
			catch(Exception ex){
				DthUtil.showMessageError();
			}
		}
	}
	public void delete() {
		AccountDAO accountDAO = new AccountDAO();
		int count = accountDAO.delete(id);
		if (count > 0)
			DthUtil.showMessageSuccess();
		else
			DthUtil.showMessageError();
	}

	public void test(){
		System.out.println("session id:"+DthUtil.getSession(DthSessionConstant.ACCOUNT_USER_ID).toString());
		System.out.println("session type:"+DthUtil.getSession(DthSessionConstant.ACCOUNT_USER_TYPE).toString());
		System.out.println("------vao day khong ");
	}
	public void onChangeCbxUserType(){
		System.out.println("---user type cbx:"+userType);
		DthUtil.setSession(DthSessionConstant.ACCOUNT_USER_TYPE, userType);
	}
	public void onChangeCbxUserId(){
		System.out.println("--user id cbx:"+userId);
		DthUtil.setSession(DthSessionConstant.ACCOUNT_USER_ID, userId);
	}
	public void update() {
		AccountDAO accountDAO = new AccountDAO();
		System.out.println("user_id:" + LoginBean.accountIdCode);
		System.out.println("pass:" + password);
		System.out.println("repass:" + rePassword);
		System.out.println("oldpass:" + old);
		Account account1 = new Account();
		for (Account temp : getListAccount()) {
			if (temp.getUserId() == LoginBean.accountIdCode) {
				account1 = temp;
			}
		}
		System.out.println(account1);
		if (old == null || old.length() == 0) {
			DthUtil.showMessage("Message", "your password is null");
		} else if (!DthUtil.convertToMD5(old).equals(account1.getUserPass())) {
			DthUtil.showMessage("Message", "your current password is wrong");
		} else if (password == null || password.length() == 0) {
			DthUtil.showMessage("Message", "your password is null");
		} else if (rePassword == null || password.length() == 0)
			DthUtil.showMessage("Message", "yourpassword is null");
		else if (!password.equals(rePassword))
			DthUtil.showMessage("Message", "2 password are not match");
		else {
			try {
				account1.setUserPass(DthUtil.convertToMD5(password));
				accountDAO.update(account1);
				DthUtil.showMessageSuccess();
			} catch (Exception ex) {
				DthUtil.showMessageError();
			}
		}
	}

	public String getOld() {
		return old;
	}

	public void setOld(String old) {
		this.old = old;
	}
}
